var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
const cors = require('cors');//引入解决跨域中间件

//引入路由
var indexRouter = require('./routes/index');
var listRouter = require('./routes/list');
var courseRouter = require('./routes/course');
var loginRouter = require('./routes/login');
var personcenterRouter = require('./routes/personcenter');

//开启服务器
var app = express();

//使用解决跨域中间件
app.use(cors());

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

//设置post参数获取的响应头
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
//cookie
app.use(cookieParser());
//开放静态资源
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));

//使用路由
app.use('/api', indexRouter);
app.use('/api', listRouter);
app.use('/api', courseRouter);
app.use('/api', loginRouter);
app.use('/api', personcenterRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  res.status(404);
  res.send({
    code: 404,
    msg: 'Not Found'
  })
});

// error handler
app.use(function (err, req, res, next) {
  res.send({
    code: 500,
    msg: err
  })
});

module.exports = app;
